import React from "react";
import { UserApp, UserProfile } from "../../../serve/interface";
import { Checkbox, Form, Input, message, Modal } from "antd";
import { apis } from "../../apis";
import { validteUserApp } from "../../../serve/validators/app";
import UserSelect from "./UserSelect";

interface ModalAppProps {
    app?: UserApp;
    btn: React.ReactNode;
    profile: UserProfile;
    onChange: (profile: UserProfile) => void;
}
export const ModalApp = (props: ModalAppProps) => {
    const { app, profile, btn } = props;
    const [open, setOpen] = React.useState(false);
    const [form] = Form.useForm<UserApp>();
    React.useEffect(() => {
        if (open) {
            if (app) {
                form.setFieldsValue(app);
            } else {
                form.resetFields();
            }
        }
    }, [app, open]);

    const onFinish = async () => {
        const values = await form.validateFields();
        const params = app ? { ...app, ...values } : values;
        const error = validteUserApp(params, profile.apps);
        if (error) {
            message.error(error);
            return;
        }
        const res = app ? await apis.update_app({
            ...app,
            ...values,
        }) : await apis.create_app(values);
        if (res.success) {
            props.onChange(res.data);
            setOpen(false);
        } else {
            message.error(res.message);
        }
    };
    return <>
        <span onClick={() => setOpen(true)}>{btn}</span>
        <Modal 
            open={open}
            title={app ? "编辑站点" : "新建站点"}
            onOk={onFinish}
            onCancel={() => setOpen(false)}
        >
            <Form form={form} onFinish={onFinish} labelCol={{ span: 5 }} className="pt-4">
                <Form.Item label="站点标题" name="title" rules={[{ required: true, message: "请输入站点标题" }]}>
                    <Input />
                </Form.Item>
                <Form.Item label="站点描述" name="description">
                    <Input.TextArea rows={5}/>
                </Form.Item>
                <Form.Item label="启用目录" name="hideParent" valuePropName="checked" tooltip="开启后非叶子节点的文档将不可点击">
                    <Checkbox />
                </Form.Item>
                {app && <Form.Item label="共享用户" name="editors">
                    <UserSelect mode="multiple" />
                </Form.Item>}
            </Form>
        </Modal>
    </>;
};